from flask import current_app, jsonify, app
from flask import g
from flask import redirect
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import News, Category, User
from info.modules.index import index_blue
from info.modules.user import user_blue
from info.utils.common import get_login_info
from info.utils.image_storage import storage
from info.utils.response_code import RET
from flask import render_template


@user_blue.route('/user_index')
@get_login_info
def index():
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user_info': user.to_dict()
    }
    return render_template('news/user.html', data=data)


@user_blue.route('/base_info', methods=['GET', 'POST'])
@get_login_info
def base_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={"user": user.to_dict()})

    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")
    signature = request.json.get("signature")

    if not all([nick_name, gender, signature]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3. 更新并保存数据
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 将 session 中保存的数据进行实时更新
    session["nick_name"] = nick_name

    # 4. 返回响应
    return jsonify(errno=RET.OK, errmsg="更新成功")


@user_blue.route('/pic_info', methods=["GET", "POST"])
@get_login_info
def pic_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pic_info.html', data={"user_info": user.to_dict()})

    try:
        avatar_data = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        avatar_name = storage(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传七牛云错误')
    user.avatar_url = avatar_name
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='上传数据库错误')
    data = {"avatar_url": constants.QINIU_DOMIN_PREFIX + avatar_name}
    return jsonify(errno=RET.OK, data=data)


@user_blue.route('/pass_info', methods=['GET', "POST"])
@get_login_info
def pass_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
        #
        # input_password = request.json.get('first_password')
        # second_password = request.json.get('second_password')
        # confirm_password = request.json.get('confirm_password')
        # if not all([input_password, second_password, confirm_password]):
        #     return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
        # # 判断原密码是否正确
        # if not user.check_passowrd(input_password):
        #     return jsonify(errno=RET.DBERR, errmsg="密码错误")
        # # 比较两次密码
        # if second_password != confirm_password:
        #     return jsonify(errno=RET.PARAMERR, errmsg='两次密码不一致')
        # # 更新数据库
        # try:
        #     user.password_hash = second_password
        #     db.session.commit()
        # except Exception as e:
        #     current_app.logger.error(e)
        #     db.session.rollback()
        #     return jsonify(errno=RET.DBERR, errmsg='更新密码出错')
        # return jsonify(errno=RET.OK, errmsg='更新密码成功')
        # 1. 获取到传入参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 2. 获取当前登录用户的信息

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

    # 更新数据
    user.password = new_password

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg="保存成功")


@user_blue.route('/collection')
@get_login_info
def collection():
    user = g.user
    # 相应前端第几页的按钮
    page = request.args.get("page", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 查询
    per_page = request.args.get('per_page', 5)  # 默认每页加载5条
    # # 查询用户指定页数的收藏新闻
    # current_page = 1
    # total_page = 1
    try:
        paginate = user.collection_news.paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')
    # 获取查询后的数据
    items = paginate.items
    # 获取总页码
    total_page = paginate.pages
    # 获取当前页码
    current_page = paginate.page
    collection_list = []
    for news in items:
        collection_list.append(news.to_basic_dict())
    print(collection_list)
    data = {'collection_list': collection_list,
            'total_page': total_page,
            'current_page': current_page,
            }
    return render_template('news/user_collection.html', data=data)


@user_blue.route('/news_release', methods=['GET', 'POST'])
@get_login_info
def news_release():
    if request.method == 'GET':
        categories = []
        try:
            # 获取所有的分类数据
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        # 定义列表保存分类数据
        categories_dicts = []

        for category in categories:
            # 获取字典
            cate_dict = category.to_dict()
            # 拼接内容
            categories_dicts.append(cate_dict)

        # 移除`最新`分类
        categories_dicts.pop(0)
        # 返回内容
        return render_template('news/user_news_release.html', data={"categories": categories_dicts})

    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
    image = None
    if not all([title, source, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 1.2 尝试读取图片

    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content

    if index_image:
        image_data = index_image.read()
    else:
        try:
            with open('info/static/news/images/haha.png', 'r') as f:

                image_data = f.read('rb')


        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
            # 2. 如果有图片将标题图片上传到七牛
    try:
        key = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

    news.category_id = category_id
    news.user_id = g.user.id
    # 1代表待审核状态
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
        # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


@user_blue.route('/news_list')
@get_login_info
def news_list():
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, 2, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return render_template('news/user_news_list.html', data=data)
